/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.ycl.wx.audio.yzserver.handler;

import cn.ac.iie.di.ban.ycl.wx.audio.yzserver.common.RuntimeEnv;
import cn.ac.iie.di.ban.ycl.wx.audio.yzserver.utils.CurrentTimeutil;
import cn.ac.iie.di.ban.ycl.wx.audio.yzserver.utils.HttppostUtil;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import com.alibaba.fastjson.JSONObject;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

/**
 *
 * @author Administrator
 */
public class AudioHandler implements HandlerI {

    static Logger logger = Logger.getLogger(AudioHandler.class.getName());

    @Override
    public void init() throws Exception {
    }

    @Override
    public void execute(Request arg0, HttpServletRequest arg1, HttpServletResponse arg2) throws Exception {
        ServletOutputStream out = arg2.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        long reqtime = CurrentTimeutil.currentTime();//能保持唯一性？
        HttpPost httppost1 = null;
        HttpClient httpClient1 = null;
        try {

            String audioReq = ParseRequestStream.parseRequestStreamAsString(arg0.getInputStream());
            logger.info(reqtime + " receive request : " + audioReq);
            String reponseCode = "";//错误返回码
            InputStream inputStream = null;//返回流
            //解析json获取url，md5获取文件名
            if (RuntimeEnv.wxAudioUrlQueryLimit.get() < Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.WXAUDIOLIMIT))) {
                RuntimeEnv.wxAudioUrlQueryLimit.incrementAndGet();
                try {
                    JSONObject reqJson = JSONObject.parseObject(audioReq);

                    try {
                        httpClient1 = new DefaultHttpClient();
                        //设置超时5s
                        httpClient1.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 180);
                        httpClient1.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000 * 180);
                        httppost1 = new HttpPost((String) RuntimeEnv.getParam(RuntimeEnv.URL_SB));
//                        StringEntity reqEntity = new StringEntity(reqJson.toJSONString(), Charset.forName("UTF-8"));
//                        reqEntity.setContentType("application/json");// 区分不同种类的数据,xml数据
//                        httppost1.setEntity(reqEntity);
//                        HttpResponse response = httpClient1.execute(httppost1);
//                        StatusLine sl = response.getStatusLine();
                        logger.info(reqtime + " send " + reqJson.toJSONString());
                        InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(reqJson.toJSONString().getBytes("UTF-8")), -1);
                        reqEntity.setContentType("application/octet-stream");// 区分不同种类的数据,xml数据
                        reqEntity.setContentEncoding("UTF-8");// charset=UTF-8
                        httppost1.setEntity(reqEntity);

                        HttpResponse response = httpClient1.execute(httppost1);
                        StatusLine sl = response.getStatusLine();
                        logger.info(sl);
                        if (sl.getStatusCode() == 200) {
                            inputStream = response.getEntity().getContent();
                        } else {
                            inputStream = response.getEntity().getContent();
                            logger.warn(reqtime + ",response code is " + sl.getStatusCode()); //                System.out.println(response.toString());
                        }
                    } catch (IOException ex) {
                        reponseCode = "{\"code\":-5,\"errorinfo\":\"网闸未返回文件，请稍候重试\"}";
                        logger.error(reqtime + " httpClient exception:" + ex.getMessage(), ex);
                    } finally {
//                        httppost1.releaseConnection();
//                        httpClient1.getConnectionManager().shutdown();
                    }
//                    inputStream = HttppostUtil.sendJson(audioReq, (String) RuntimeEnv.getParam(RuntimeEnv.URL_SB));
                } catch (NumberFormatException e) {
                    reponseCode = "{\"code\":-5,\"errorinfo\":\"网闸未返回文件，请稍候重试\"}";
                    logger.error(reqtime + "request is not a json,reutrn..." + e.getMessage(), e);
                }
            } else {
                reponseCode = "{\"code\":-4,\"errorinfo\":\"查询访问量超出最大并发，请稍候重试\"}";
            }
            if (reponseCode.length() > 0 || inputStream == null) {
                logger.warn(reqtime + "get audio fail because " + reponseCode);
                inputStream = new ByteArrayInputStream(reponseCode.getBytes("UTF-8"));
            }
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;

            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            bos.flush();
        } catch (Exception e) {
            logger.error(reqtime + e.getMessage(), e);
        } finally {
            bos.close();
            httppost1.releaseConnection();
            httpClient1.getConnectionManager().shutdown();
            RuntimeEnv.wxAudioUrlQueryLimit.decrementAndGet();
            logger.info(reqtime + "use total time ms " + (System.currentTimeMillis() - reqtime));
        }
    }

}
